//
//  InterfaceController.m
//  chanlin WatchKit Extension
//
//  Created by Ryan on 15-5-9.
//  Copyright (c) 2015年 chanlin. All rights reserved.
//

#import "InterfaceController.h"
#import "NSObject+sgr.h"
#import "CLMainRowController.h"
#import "ChangyanSDK.h"



@interface InterfaceController()

@property (nonatomic,assign) NSInteger listCount;
@property (nonatomic,strong) NSArray *listData;
@property (nonatomic,strong) NSDictionary *picDic;

@property (nonatomic,unsafe_unretained)NSTimeInterval requestTime;

@property (nonatomic,unsafe_unretained) int openCount;

@end


@implementation InterfaceController

- (instancetype)init{
    self=[super init];
    
    if(self){
        
    }
    return self;
}



- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];
    self.openCount=0;
    [ChangyanSDK registerApp:@"cyruaVDf2"
                      appKey:@"9241687fc3d8cb4bcbc1ed758da47108"
                 redirectUrl:nil
        anonymousAccessToken:@"_1eNERSNS-mAYZprL3Lajn_mhGWkQXxHPqZaJ5TMpRw"];
 
    [ChangyanSDK setAllowAnonymous:YES];
    [ChangyanSDK setAllowRate:NO];
    [ChangyanSDK setAllowUpload:NO];

}

- (void)willActivate {
    [super willActivate];
    if(self.openCount==0){
        
        NSTimeInterval b=[[NSDate date] timeIntervalSince1970];
        if(fabs(b-self.requestTime)>30){
    [self performSelectorInBackground:@selector(loadData) withObject:nil];
            self.requestTime=[[NSDate date] timeIntervalSince1970];
            [self performSelectorInBackground:@selector(loadNewElement) withObject:nil];

            
            
        }
        
        
        
    }else{
        self.openCount=0;
    }
    
//    NSTimeInterval current=[[NSDate date] timeIntervalSince1970];
//    double d=[[NSUserDefaults standardUserDefaults] doubleForKey:@"clwatchGlanceDate"];
//    
//    NSInteger b=[[NSUserDefaults standardUserDefaults] integerForKey:@"clwatchDefaltTime"];
//    if(b==0||b>86400){
//        b=5;
//    }
//    
//    if(fabs(current-d)>b){
//        [self performSelectorInBackground:@selector(loadNewElement) withObject:nil];
//    }

}

- (void)handleUserActivity:(NSDictionary *)userInfo{
    NSString *url=[userInfo objectForKey:@"url"];
    NSString *type=[userInfo objectForKey:@"type"];
    if(url&&type){
        [self pushControllerWithName:@"chanlinDetail" context:@{@"url":url,@"type":type}];
    }
}

- (void)didDeactivate {
    [super didDeactivate];
}

- (void)loadData{
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://appv2.chanlin.org/e/app/list_watch.php"]];
    
   NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    if(data){
        NSObject *obj=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        NSArray *listdata=[obj sgrGetArrayForKey:@"data"];
        self.listCount=0;
        for(NSDictionary *dic in listdata){
            NSArray *list=[dic sgrGetArrayForKey:@"list"];
            self.listCount+=[list count];

        }
    
        if(self.listCount!=0){
            self.listData=listdata;
            [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
        }
        
    }
}

- (void)updateUI{
    [self.table setNumberOfRows:self.listCount withRowType:@"mainRowType"];
   NSInteger i=0;
    for(NSDictionary *dic in self.listData){
        NSArray *list=[dic sgrGetArrayForKey:@"list"];
        NSString *cTitle=[dic sgrGetStringForKey:@"cTitle"];
        BOOL b=YES;
        for(NSDictionary *dic2 in list){
            CLMainRowController *ctrl=[self.table rowControllerAtIndex:i];
            if(b){
                b=NO;
                [ctrl.topGroup setHidden:NO];
                [ctrl.className setTitle:cTitle];
            }else{
                [ctrl.topGroup setHidden:YES];
                [ctrl.className setTitle:@""];
            }
        
            NSString *str=[dic2 sgrGetStringForKey:@"titlepic"];
            [ctrl setImgUrlString:str];

            NSString *title=[dic2 sgrGetStringForKey:@"title"];
            [ctrl.titleLabel setText:title];
            i++;
        }
    }
    [self.table scrollToRowAtIndex:0];
}

- (IBAction)table:(WKInterfaceTable *)table didSelectRowAtIndex:(NSInteger)rowIndex{
    int a=0;
    NSDictionary *dataDic=nil;
    for(NSDictionary *dic in self.listData){
        NSArray *list=[dic sgrGetArrayForKey:@"list"];
        if(rowIndex<(a+list.count)){
           
            dataDic = [list sgrGetDictionaryForIndex:(int)(rowIndex-a)];
            break;
            
        }
         a+=list.count;
    }
    self.openCount=1;
    [self pushControllerWithName:@"chanlinDetail" context:dataDic];
  
    
}

- (void)loadNewElement{
    NSString *str=@"http://appv2.chanlin.org/e/app/view_watch.php";
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:str]];
    NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data){
        NSObject *obj=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSDictionary *data2=[obj sgrGetDictionaryForKey:@"data"];
        NSString *imageStr=[data2 sgrGetStringForKey:@"titlepic"];
        if(!imageStr) return;
        NSData *imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:imageStr]];
        if(!imageData) return;
        UIImage *image=[UIImage imageWithData:imageData];
        if(!image) return;
        
        NSString *url=[data2 sgrGetStringForKey:@"url"];
        
        NSString *type=[data2 sgrFGetStringForKey:@"type"];

        
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *path=[[paths sgrGetStringForIndex:0] stringByAppendingPathComponent:@"imageData"];
        
        if([[NSFileManager defaultManager] fileExistsAtPath:path]){
            [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        }
        [imageData writeToFile:path atomically:YES];
        
        if(url)
            [[NSUserDefaults standardUserDefaults] setObject:url forKey:@"clwatchDefaltUrl"];
        if(type)
            [[NSUserDefaults standardUserDefaults] setObject:type forKey:@"clwatchDefalttype"];

        
        [[NSUserDefaults standardUserDefaults] setInteger:[[obj sgrGetStringForKey:@"frequency"] integerValue]
                                                   forKey:@"clwatchDefaltTime"];
        [[NSUserDefaults standardUserDefaults] setObject:[data2 sgrGetStringForKey:@"smalltext"] forKey:@"clwatchDefaltTitle"];
        [[NSUserDefaults standardUserDefaults] setDouble:[[NSDate date] timeIntervalSince1970] forKey:@"clwatchGlanceDate"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    
}



@end



